package org.kk.ds.linked;

/**
 * 实现数据结构: 循环列表
 * @author kk
 * @Date 2021/2/4
 */
public class LoopLinked {
    private Node head;
    private int length;
    public int size(){
        return length;
    }
    public boolean isEmpty(){
        return length == 0;
    }
    public void addHead(int value){
        add(0, value);
    }
    public void addAtTail(int value){
        add(size(), value);
    }
    public void add(int index, int value){
        Node newNode = new Node(value);
        if(isEmpty()){
            head = newNode;
            head.next = head;
        }else {
            Node node = head;
            for (int i = 0; i < index-1; i++) {
                node = node.next;
            }
            newNode.next = node.next;
            node.next = newNode;
        }
        length++;
    }
    public void remove(int index){
        Node node = head;
        for (int i = 0; i < index -1; i++){
            node = node.next;
        }
        node.next = node.next.next;
        length--;
    }
    @Override
    public String toString(){
        StringBuilder builder = new StringBuilder();
        builder.append("[ ");
        Node node = head;
        while (node != null && node.next != head) {
            builder.append(node.value);
            builder.append("->");
            node = node.next;
        }
        builder.append(node.value);
        builder.append(" ]");
        return builder.toString();
    }
    class Node{
        private int value;
        private Node next;
        Node(int value){
            this.value = value;
        }
    }
}
